package com.sita.tboard.ui.activity;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.widget.TextView;

import com.sita.bike.R;
import com.sita.tboard.ActivityBase;
import com.sita.tboard.ui.fragment.TrendsImageDetailFragment;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import lecho.lib.hellocharts.view.hack.HackyViewPager;


public class ImagePagerActivity extends ActivityBase implements OnPageChangeListener {
	private static final String STATE_POSITION = "STATE_POSITION";
    public static final String EXTRA_IMAGE_INDEX = "image_index";
    public static final String EXTRA_IMAGE_URLS = "image_urls";

	@Bind(R.id.pager)
	HackyViewPager mPager;
	@Bind(R.id.indicator)
	TextView indicator;

	private int pagerPosition;

    @Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.rt_trends_image_detail_pager);

		ButterKnife.bind(this);

		pagerPosition = getIntent().getIntExtra(EXTRA_IMAGE_INDEX, 0);
        ArrayList<String> urls = (ArrayList<String>)getIntent().getSerializableExtra(EXTRA_IMAGE_URLS);

		ImagePagerAdapter mAdapter = new ImagePagerAdapter(
				getSupportFragmentManager(), urls);
		mPager.setAdapter(mAdapter);

		CharSequence text = getString(R.string.viewpager_indicator, 1, mPager
				.getAdapter().getCount());
		indicator.setText(text);

        mPager.addOnPageChangeListener(this);

		if (savedInstanceState != null) {
			pagerPosition = savedInstanceState.getInt(STATE_POSITION);
		}

		mPager.setCurrentItem(pagerPosition);
	}

    @Override
	public void onSaveInstanceState(Bundle outState) {
		outState.putInt(STATE_POSITION, mPager.getCurrentItem());
	}

    @Override
    public void onPageScrollStateChanged(int arg0) {
    }

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {
    }

    @Override
    public void onPageSelected(int arg0) {
        CharSequence text = getString(R.string.viewpager_indicator,
                arg0 + 1, mPager.getAdapter().getCount());
        indicator.setText(text);
    }

    @Override
    protected void onDestroy() {
        if (mPager != null){
            mPager.removeOnPageChangeListener(this);
        }
        super.onDestroy();
    }

    private class ImagePagerAdapter extends FragmentStatePagerAdapter {

		public ArrayList<String> fileList;

		public ImagePagerAdapter(FragmentManager fm, ArrayList<String> fileList) {
			super(fm);
			this.fileList = fileList;
		}

		@Override
		public int getCount() {
			return fileList == null ? 0 : fileList.size();
		}

		@Override
		public Fragment getItem(int position) {
			String url = fileList.get(position);
			return TrendsImageDetailFragment.newInstance(url);
		}

	}
}